package com.gjsrmyy.edi.utils;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import org.xml.sax.SAXException;

import java.io.OutputStream;
import java.util.regex.Pattern;

public class CDataContentHandler extends XMLSerializer {
    private static final Pattern XML_CHARS = Pattern.compile("[<>&]");

    public CDataContentHandler(OutputStream output, OutputFormat format ) {
        super(output,format);
    }

    public void characters(char[] ch, int start, int length) throws SAXException {
        boolean useCData = XML_CHARS.matcher(new String(ch, start, length)).find();
        if (useCData) super.startCDATA();
        super.characters(ch, start, length);
        if (useCData) super.endCDATA();
    }

}
